﻿using System;
using System.Collections;
using System.Data;
using System.Drawing;
using System.Windows.Forms;
using CXMLStudioIDE.Common.Entities;
using CXMLStudioIDE.DataAccessLayer;
using CXMLStudioIDE.WinFormsUI.CXMLStudioControls;

namespace CXMLStudioIDE.Forms
{
    public partial class AddInstanceForm : Form
    {
        #region Delegates

        public delegate void OnAddInstanceEventHandler(object sender, AddInstanceArgs args);

        #endregion

        private readonly Size BIG_SIZE = new Size(640, 618);
        private readonly Size SMALL_SIZE = new Size(640, 380);
        private readonly Hashtable hsh_entity;
        private readonly CXMLStudioDAL m_dal;
        private readonly MainForm m_mainform;
        private EntityType m_entitytype;

        public enum AddInstanceMode
        {
            None = 0,
            New = 1,
            Open = 2,
            Existing = 3
        }

        #region Constructors

        public AddInstanceForm(MainForm mainform, CXMLTreeNode parentnode)
        {
            InitializeComponent();
            ParentNode = parentnode;
            hsh_entity = new Hashtable();
            txtEntityName.Text = ParentNode.Name;
            m_dal = new CXMLStudioDAL();
            LoadContextDDL();
            rb_New.Enabled = false;
            rb_Existing.Enabled = false;
            rb_Open.Enabled = false;
            dgv_Version.Enabled = false;
            m_mainform = mainform;
            rb_New.Checked = true;
            btnOk.Enabled = false;
        }

        #endregion

        #region Properties

        public CXMLTreeNode ParentNode { get; set; }
        public bool IsBig { get; set; }
        public AddInstanceMode Mode { get; set; }

        #endregion

        public event OnAddInstanceEventHandler OnAddInstance;

        private void cmbContext_SelectedIndexChanged(object sender, EventArgs e)
        {
            hsh_entity.Clear();
            string sZ_EntityTypeName = null;
            DataSet dsEntities = m_dal.GetBusinessEntitiesInContext((int) cmbContext.SelectedValue);
            if (dsEntities != null && dsEntities.Tables.Count > 0 &&
                dsEntities.Tables[0].Rows.Count > 0)
            {
                foreach (DataRow row in dsEntities.Tables[0].Rows)
                {
                    sZ_EntityTypeName = row["vch_Name"].ToString();
                    switch (ParentNode.Name)
                    {
                        case "Places":
                            if (sZ_EntityTypeName.Equals("PlaceType"))
                            {
                                m_entitytype = new EntityType();
                                m_entitytype.EntityTypeName = sZ_EntityTypeName;
                                m_entitytype.EntityTypeID = (int) row["idgk_EntityTypeID"];
                            }
                            break;
                    }
                    if (m_entitytype != null && m_entitytype.EntityTypeID > 0)
                    {
                        LoadVersionsGrid(m_entitytype.EntityTypeID);
                    }
                    hsh_entity.Add(row["idgk_EntityTypeID"].ToString(), row["vch_Name"].ToString());
                }
                dgv_Version.Enabled = true;
            }
            else
            {
                dgv_Version.DataSource = "";
                dgv_ExistingInstances.DataSource = "";
                rb_Existing.Enabled = false;
                rb_New.Enabled = false;
                rb_Open.Enabled = false;
                btnOk.Enabled = false;
            }
        }

        private void rb_Existing_CheckedChanged(object sender, EventArgs e)
        {
            if(rb_Existing.Checked)
            {
                pnlExistingInstances.Visible = true;
                btnOk.Text = "Add selected instances";
                btnOk.Width = 130;
                ClientSize = BIG_SIZE;
                IsBig = true;
                btnOk.Top = pnlExistingInstances.Bottom + 20;
                btnOk.Left = pnlExistingInstances.Right - btnOk.Width;
                btnCancel.Top = pnlExistingInstances.Bottom + 20;
                btnCancel.Left = btnOk.Left - btnCancel.Width - 30;
                Mode = AddInstanceMode.Existing;
                PopulateExistingInstancesGrid((int)dgv_Version.SelectedRows[0].Cells["EntityID"].Value);
                btnOk.Enabled = true;
            }
            
        }

        private void rb_Open_CheckedChanged(object sender, EventArgs e)
        {
            if(rb_Open.Checked)
            {
                ConfigureSmall();
                Mode = AddInstanceMode.Open;
                btnOk.Enabled = true;
            }
        }

        private void PopulateExistingInstancesGrid(int  EntityId)
        {
            BindingSource bs = new BindingSource();
            dsExistingInstances = m_dal.GetEntityInstances(EntityId);
            bs.DataSource = dsExistingInstances;
            bs.DataMember = dsExistingInstances.Tables[0].TableName;
            dgv_ExistingInstances.DataSource = bs;
            ConfigureExistingInstancesGrid();
        }
        private void ConfigureExistingInstancesGrid()
        {
            foreach (DataGridViewColumn col in dgv_ExistingInstances.Columns)
            {
                if (!col.Name.Equals("EntityInstanceDescription"))
                {
                    col.Visible = false;
                }
            }
            dgv_ExistingInstances.AutoResizeColumns();
        }

        private void rb_New_CheckedChanged(object sender, EventArgs e)
        {
            if (rb_New.Checked)
            {
                ConfigureSmall();
                Mode = AddInstanceMode.New;
                btnOk.Enabled = true;
            }
        }
        private void ConfigureSmall()
        {
            btnOk.Text = "Next >>";
            btnOk.Width = 70;
            ClientSize = SMALL_SIZE;
            IsBig = false;
            btnOk.Top = pnlMain.Bottom + 10;
            btnOk.Left = pnlMain.Right - btnOk.Width;
            btnCancel.Top = pnlMain.Bottom + 10;
            btnCancel.Left = btnOk.Left - btnCancel.Width - 30;
        }

        private BusinessEntity BuildBusinessEntity()
        {
            BusinessEntity be = null;
            if (m_entitytype != null)
            {
                DataGridViewSelectedRowCollection rows = dgv_Version.SelectedRows;
                DataGridViewRow row = null;
                if (rows.Count > 0)
                {
                    row = rows[0];
                    be = new BusinessEntity();
                    be.Name = m_entitytype.EntityTypeName;
                    be.EntityType.EntityTypeID = m_entitytype.EntityTypeID;
                    be.EntityVersion.EntityVersionID = (int) row.Cells["idgk_EntityVersionID"].Value;
                    be.EntityTypeVersions.EntityTypeVersionsID = (int) row.Cells["idgk_EntityTypeVersionsID"].Value;
                    be.EntityVersion.FullVersion = row.Cells["VersionNumber"].Value.ToString();
                    be.EntityType.EntityTypeContextID = (int) row.Cells["EntityTypeContextID"].Value;
                    be.EntityType.EntityTypeContextName = row.Cells["EntityTypeContextName"].Value.ToString();
                    be.ID = (int) row.Cells["EntityID"].Value;
                    return be;
                }
            }
            return null;
        }

        private void btnOk_Click(object sender, EventArgs e)
        {
            if (!IsBig && cmbContext.SelectedIndex > 0 && dgv_Version.SelectedRows.Count > 0
                && (rb_Existing.Checked || rb_New.Checked))
            {
                BusinessEntity be = BuildBusinessEntity();
                if (be != null && m_mainform != null)
                {
                    OnAddInstance(this,
                                  new AddInstanceArgs(be, ParentNode, (GoldEntryForm) m_mainform.ActiveMdiChild,Mode));
                    Dispose();
                }
            }
            else
            {
                MessageBox.Show(this, "Please select context,version", "CXMLStudioIDE", MessageBoxButtons.OK,
                                MessageBoxIcon.Exclamation);
            }
        }

        #region Methods

        private void LoadContextDDL()
        {
            dsContext = m_dal.GetContext();
            cmbContext.DisplayMember = dsContext.Tables[0].Columns[1].ColumnName;
            cmbContext.ValueMember = dsContext.Tables[0].Columns[0].ColumnName;
            cmbContext.DataSource = dsContext.Tables[0];
        }
        private void ConfigureVersionsGrid()
        {
            foreach (DataGridViewColumn col in dgv_Version.Columns)
            {
                    col.Visible = false;
            }
            dgv_Version.Columns["EntityName"].Visible = true;
            dgv_Version.Columns["VersionNumber"].Visible = true;
            dgv_Version.Columns["EntityName"].DisplayIndex = 0;
            dgv_Version.Columns["VersionNumber"].DisplayIndex = 1;
            dgv_ExistingInstances.AutoResizeColumns();
        }

        private void LoadVersionsGrid(int i_EntityTypeID)
        {
            dsVersion = m_dal.GetBusinessEntityInContextVersion(i_EntityTypeID);
            if (dsVersion.Tables.Count > 0 && dsVersion.Tables[0].Rows.Count > 0)
            {
                dgv_Version.DataSource = dsVersion.Tables[0];
                rb_Existing.Enabled = true;
                rb_New.Enabled = true;
                rb_Open.Enabled = true;
                ConfigureVersionsGrid();
            }
            else
            {
                dgv_ExistingInstances.DataSource = "";
            }
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            Dispose();
        }

        #endregion

        private void rb_New_MouseHover(object sender, EventArgs e)
        {
            toolTip1.SetToolTip(sender as RadioButton,"Opens an empty Gold Entry form");
        }

        private void rb_Open_MouseHover(object sender, EventArgs e)
        {
            toolTip1.SetToolTip(sender as RadioButton,"Opens a Gold Entry form to load an existing instance \n");
        }

        private void rb_Existing_MouseHover(object sender, EventArgs e)
        {
            toolTip1.SetToolTip(sender as RadioButton, "Displays a gridview to select one or many existing instances \n" +
                    " to add them to the parent entity");
        }

        private void dgv_Version_SelectionChanged(object sender, EventArgs e)
        {
            if(rb_Existing.Checked && dgv_Version.SelectedRows.Count > 0)
            {
                PopulateExistingInstancesGrid((int)dgv_Version.SelectedRows[0].Cells["EntityID"].Value);
            }
        }
    }
    public class AddInstanceArgs
    {
        public AddInstanceArgs(BusinessEntity be, CXMLTreeNode inCallingNode, GoldEntryForm inCallingForm, CXMLStudioIDE.Forms.AddInstanceForm.AddInstanceMode mode)
        {
            BusinessEntity = be;
            CallingNode = inCallingNode;
            CallingGoldForm = inCallingForm;
            Mode = mode;
        }
        public GoldEntryForm CallingGoldForm { get; set; }
        public CXMLTreeNode CallingNode { get; set; }
        public BusinessEntity BusinessEntity { get; set; }
        public CXMLStudioIDE.Forms.AddInstanceForm.AddInstanceMode Mode { get; set; }
    }
}